package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @作者 itcast
 * @创建日期 2021/4/20 9:35
 **/
@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    ApUserMapper apUserMapper;


    @Override
    public ResponseResult login(LoginDto dto) {
        // 1. 参数校验  ( 设备ID     (手机号 和 密码))
        if(dto.getEquipmentId() == null && (StringUtils.isBlank(dto.getPhone()) || StringUtils.isBlank(dto.getPassword())) ){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"设置ID 或 用户名密码 必须得有一项");
        }
        if(StringUtils.isNotBlank(dto.getPhone())&&StringUtils.isNotBlank(dto.getPassword())){
            // 2. 有(手机号 和 密码)  实现用户登录
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getPhone, dto.getPhone())
                    .eq(ApUser::getStatus,0)
            );
            if(apUser == null){
                throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在");
            }
            // 数据库加密的密码
            String password = apUser.getPassword();
            String inputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
            if(password.equals(inputPwd)){
                // 登录成功  颁发token
                String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
                Map map = new HashMap();
                map.put("token",token);
                apUser.setPassword("");
                apUser.setSalt("");
                map.put("user",apUser);
                return ResponseResult.okResult(map);
            }else {
                throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码不正确");
            }
        }else {
            // 3. 有设备ID  直接颁发jwtToken userId存储 0
            String token = AppJwtUtil.getToken(0L);
            Map map = new HashMap();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
